import asyncio
import json
import random

from rms_apix import RmsApiX

device_nos = {
"HO3N00JZ2MP069UYAQZ861XYNI3V6VS529L0A4I": None,
"I821VHHTY71ZIYMF2IBWPLHH9D7WY0SW5FQX5BD": None,
"E7CIMLIT9TNGCCLRE1UGHXNP4WG6NU0UYN19INQ": None,
"95X18UBQAOZJ9VSD3GG2M3ZL6UZH61EK1GXISUR": None,
"DK50LRZTLDO1NPJJQTS6F3922UM2HIRNLIGOMYS": None,
"KQD3M7PPLWJBS9P8N4VFYEYZE2MV94XPWRU4PIZ": None,
"HIMHIADLSJ8EIKZP6DCC7XWL0SJT239W85PI8QO": None,
"HHNXTL61OU3FW0CU8GQF6NKG9WGCP184B2ZVH35": None,
"GYPMIYQ5RF12E18L9I7XPDZD62H5T1Q8Z6JVJWE": None,
"T9GSJNUXL7N7GM1RVET6DDZR34BD5021SODYUAP": None,
"RGEIHOYVYTL7GS8OY7R68WN44KJYP6HZHEW1SD9": None,
"ZZVONNTWA3UV774SNYZHT0QHX26QMV2HWBHTHH7": None,
"1OCVQ4R5HEPACAODH6TSSBHLYKZ7FE64CCQO2AG": None,
"09MS9DJSOTVLSFTNWV96TEJGCR3CDXPMJ7B4FRF": None,
"7CTZ5UZ3AAYHISEY8WJFAUA6FA4RKN3NYZU1C2T": None,
"FLS3JRU7TZPCT4LVTBE3M8GSKG56IQ9VL343AP1": None,
"VB5ZDBW6CP6PDPVYGFB2B525WN06WAB94LTB2Q3": None,
"O9X24520CKB20UT4P0AVCDVQHLICNUOU9SATYLF": None,
"64N1X18TY8MWBCS10F4LPQFYQX4VXS0AKKZWWJB": None,
"DPID48N6AKTOYYPSXVLRFY12FL4N7JOA2E3QX91": None,
"LL2F0G6QI9P2HDQHWO9TCK55TR35W2GCIGESSED": None,
"JAJCCN02HSN9XA9JK3EHU0324OBQ712LW0MLXIW": None,
"AJV7W2YRGGP606G0Q4O36JNG2FBDCMFJ5SOE87Z": None
}


async def inner_bind_device(rms_apix, devices , login_token):
    device_count = len(devices)
    device_no_count = len(device_nos)
    if device_count > device_no_count:
        print(f"-----绑定信息不匹配-------")
    else:
        specified_device_numbers = {key: value for key, value in device_nos.items() if value is not None}
        other_device_numbers = {key: value for key, value in device_nos.items() if value is None}
        specified_devices = [item for item in devices if item["qualitylocationId"] in specified_device_numbers.values()]
        other_devices = [item for item in devices if item["qualitylocationId"] not in specified_device_numbers.values()]

        random_keys = random.sample(list(other_device_numbers.keys()), len(other_devices))
        random_device_numbers = {k: other_device_numbers[k] for k in random_keys}
        print(f"-----specified_devices size:{len(specified_devices)}-------")
        print(f"-----random_devices size:{len(other_devices)}-------")
        print(f"{specified_device_numbers}")
        print(f"{random_device_numbers}")
        print(f"{specified_devices}")
        print(f"{other_devices}")

        print(f"------------------------------------------------------------")
        print(f"---------------------------分割线----------------------------")
        print(f"------------------------------------------------------------")

        await do_bind_things(rms_apix,login_token, specified_device_numbers, specified_devices)
        await do_bind_things(rms_apix, login_token, random_device_numbers, other_devices)


async def do_bind_things(rms_apix,login_token, device_numbers, devices):
    index = 0
    for key, value in device_numbers.items():
        find_device = None
        if value:
            find_devices = [item for item in devices if int(item['qualitylocationId']) == int(value)]
            if find_devices:
                find_device = find_devices[0]
                index += 1
        else:
            find_device = devices[index]
            index += 1

        if find_device:
            device_id = find_device['qualitylocationId']
            device_name = find_device['qualitylocationName']
            qr_content = await rms_apix.get_bind_qrcode()
            report_res = await rms_apix.report_device_info(qr_content, key)
            # print(f"---qr_content:{qr_content}, key:{key}")
            if report_res == "操作成功":
                bind_respond = await rms_apix.bind_device_new(login_token, key, find_device)
                print( f"-----device_id:{device_id}, device_name: {device_name}, device_no: {key} , bind_respond: {bind_respond}----")
                pass

async def load_line_info(rms_apix,admin_login_token, factory_id, line_id):
    """ 获取产线信息 """
    # 获取产线机位列表
    if factory_id is None or line_id is None:
        print(f"-------factory_id 或 line_id 不能为空---------")
        return

    lines_info = await rms_apix.get_lines(admin_login_token, factory_id, line_id)
    if lines_info is not None and len(lines_info) > 0:
        line_info = lines_info[0]
        return line_info

    return None



async def load_line_device_conig_info(rms_apix , line_token):
    line_config = await rms_apix.load_line_config_by_token(line_token)
    print(f"----line_config: {json.dumps(line_config)}")
    devices = line_config["qualitylocationList"]
    return devices


async def bind_device(rms_apix):
    """
        绑定机位
        TR_LA_001: 1eb7fb9a-a514-4553-8631-8b095ba711e0
        TR_LA_002: 4505bede-f7dd-4a65-ab5e-7d9a68129508
        TR_LA_003: de4183bc-c71a-40e7-9968-ed76992f3472
        """
    line_token = "9c572d2c-990f-4413-8727-14923ab9f837"
    # 厂长登录Token
    login_token =  "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjIzMWM5OWRjLTRhNmUtNDRjOC1iMDI1LTJiODg0OTMzMmNjYiJ9.08wDCoSWACpomcs1_wB7qRGIn6Y0PsL5ALol47U5iOYMxIKycda7oke10OlU8SlzMe5DzGPoN6IPLdmPZ4OJEg"

    devices = await load_line_device_conig_info(rms_apix, line_token)
    print(f"---devices: {json.dumps(devices)}")
    none_bind_devices = [device for device in devices if device['deviceNo'] is None]
    await inner_bind_device(rms_apix, none_bind_devices, login_token)


async def do_default_config(rms_apix, admin_login_token, position):
    """ 设置机位信息的初始化 """
    default_capture_config = dict(
        light = False,
        captureType = 2,
        inUse = True,
        focus = "2.78",
        exposure = "1000000",
        adjust_exposure = 1000000,
        adjust_delay = "50",
        area_delay = "400",
        is_adjust = True
    )
    matrix = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
    default_ai_matrix = dict(matrix = json.dumps(matrix))

    location_rel_id = position["machineLocationRelId"]
    device_id = position["qualitylocationId"]
    modal_position_info = await rms_apix.get_model_position_info(admin_login_token, location_rel_id)
    template_data = modal_position_info["templateData"]
    config_json = list()

    config_info_list:list[dict] = list()
    defective_info_list = list()
    for template_data_item in template_data:
        capture_region_id = template_data_item["captureRegionId"]
        capture_region_name = template_data_item["captureRegionName"]
        defective_code = template_data_item["defectiveProductsCode"]
        defective_name = template_data_item["defectiveProductsName"]
        defective_rel_ids = template_data_item["defectiveProductsDefectiveRelIds"]
        defective_rel_names = template_data_item["defectiveProductsDefectiveRelNames"]

        config_info_item = dict(captureRegionId = capture_region_id)
        config_info_item["captureRegion"] = dict(
            captureRegionId = capture_region_id,
            captureRegionName = capture_region_name,
            config = json.dumps(default_capture_config))
        config_info_item["defectiveProductss"] = list()
        config_info_list.append(config_info_item)

        defective_item = dict(
            captureRegionId = capture_region_id,
            defectiveProductsCode = defective_code,
            defectiveProductsName = defective_name,
            defectiveProductsDefectiveRelIds = defective_rel_ids,
            defectiveProductsDefectiveRelNames = defective_rel_names,
            config = json.dumps(default_ai_matrix)
        )
        defective_info_list.append(defective_item)

    unique_config_info_data = {item['captureRegionId']: item for item in config_info_list}.values()
    # 将结果转换回列表
    config_info_list:list[dict] = list(unique_config_info_data)
    for unique_config_info_item in config_info_list:
        capture_region_id = unique_config_info_item["captureRegionId"]
        for defective_info_item in defective_info_list:
            if "captureRegionId" not in defective_info_item:
                continue
            defective_belong_region_id = defective_info_item["captureRegionId"]
            if capture_region_id == defective_belong_region_id:
                defective_list = unique_config_info_item["defectiveProductss"]
                defective_info_item.pop("captureRegionId")
                defective_list.append(defective_info_item)

    for item in config_info_list:
        item.pop("captureRegionId")

    config_json.extend(config_info_list)

    result = await rms_apix.init_default_config(admin_login_token, location_rel_id, json.dumps(config_json))
    print(f"-----device_id:{device_id} , 结果: {result}")

async def init_config(rms_apix):
    """ 绑定完以后，需要初始化机位的一些配置信息 """
    factory_id = 1
    line_id = 47
    # 管理员登录Token
    admin_login_token = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjIzMWM5OWRjLTRhNmUtNDRjOC1iMDI1LTJiODg0OTMzMmNjYiJ9.08wDCoSWACpomcs1_wB7qRGIn6Y0PsL5ALol47U5iOYMxIKycda7oke10OlU8SlzMe5DzGPoN6IPLdmPZ4OJEg"

    line_info = await load_line_info(rms_apix, admin_login_token, factory_id, line_id)
    if line_info:
        # 机位信息
        position_infos = line_info["aiMachineLocationRelVoList"]
        for position in position_infos:
            await do_default_config(rms_apix, admin_login_token, position)

async def main():
    rms_apix = RmsApiX()
    # await bind_device(rms_apix)
    await init_config(rms_apix)







if __name__ == '__main__':
    asyncio.run(main())